package com.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import com.web.VO.*;
import com.web.annotation.CurrentUser;
import com.web.annotation.LoginRequired;
import com.web.domain.Response;
import com.web.entity.*;
import com.web.service.*;
import com.web.utils.GetLocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/app")
public class HomeController extends BaseController {

    @Autowired
    private HomeService homeService;
    @Autowired
    private SupplyService supplyService;
    @Autowired
    private JobService jobService;
    @Autowired
    private UserDataService userDataService;
    @Autowired
    private AskQuestionsService askQuestionsService;
    @Autowired
    private DemandService demandService;

    /**
     * 获取首页信息
     * @return
     */
    @PostMapping("/home/info")
    @ResponseBody
    @LoginRequired
    public Response getUserInfo(){
        Map<String,Object> map = new HashMap<>();
        map.put("banner",homeService.allBanner());
        map.put("news",homeService.allNews());
        map.put("customerServiceMobile",getMarginInfo().getCustomerServiceMobile());
        return Response.custom().ok().addParams(map);
    }


    /**
     * 需求列表
     * @return
     */
    @PostMapping("/home/Demand")
    @ResponseBody
    @LoginRequired
    public Response getDemand(Integer pageNum){
        if (pageNum == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        PageHelper.startPage(pageNum,10);
        List<DemandInfo> list = homeService.getAllDemandInfo();
        PageInfo pageInfo = new PageInfo(list,10);
        if(pageNum > pageInfo.getPages()){
            return Response.custom().ok().addParams(new List[0]);
        }else{
            return Response.custom().ok().addParams(pageInfo.getList());
        }
    }

    /**
     * 获取需求信息详情
     * @param info
     * @param demandId
     * @return
     */
    @PostMapping("/demand/details")
    @ResponseBody
    public Response getDemandInfoDetails(@CurrentUser UserInfo info,Integer demandId){
        if (demandId == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        DemandInfoDetails demandInfoDetails = homeService.getDemandInfoDetails(demandId,info.getUserId());
        demandInfoDetails.setCity(GetLocation.getCityName(GetLocation.getAdd(demandInfoDetails.getLongitude(),demandInfoDetails.getLatitude())));
        if (demandInfoDetails == null){
            return Response.custom().failure("没有找到该需求信息!");
        }
        return Response.custom().ok().addParams(demandInfoDetails);
    }

    /**
     * 我要接单
     * @return
     */
    @RequestMapping("/demand/accept")
    public Response accept(@CurrentUser UserInfo info, Integer demandId) {
        UserInfo userInfo = infoService.info("user_id",info.getUserId());
        if ("2".equals(userInfo.getIsVip().toString())) {
            return Response.custom().failure("不是VIP，不能进行接单操作！");
        }
        DemandInfo demandInfo = homeService.findDemandInfoById(demandId);
        if (demandInfo.getUserId().equals(info.getUserId())) {
            return Response.custom().failure("该需求是你自己创建的，不能接收自己的需求！");
        }
        if (demandInfo.getIsInvalid() != 2) {
            return Response.custom().failure("该需求已失效，不能进行接单操作！");
        }
        if (demandService.getOne(new DemandAccept(demandId, info.getUserId())) != null) {
            return Response.custom().failure("您已接单不能重复接单！");
        }
        Integer id = demandService.acceptDemand(info, demandId);
        if (id != null) {
            return Response.custom().ok();
        } else {
            return Response.custom().failure("接单失败！");
        }
    }

    /**
     * 我的接单
     * @param info
     * @return
     */
    @RequestMapping("/demand/myAccept")
    public Response findMyDemand(@CurrentUser UserInfo info, Integer pageNum) {
        if (pageNum == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        PageHelper.startPage(pageNum, 10);
        List<MyDemandVO> list = demandService.listMyDemand(info.getUserId());
        PageInfo pageInfo = new PageInfo(list,10);
        if(pageNum > pageInfo.getPages()){
            return Response.custom().ok().addParams(new List[0]);
        }else{
            return Response.custom().ok().addParams(pageInfo.getList());
        }
    }

    /**
     * 我的发布
     * @param userInfo
     * @return
     */
    @RequestMapping("/home/myPublish")
    public Response findMyPublish(@CurrentUser UserInfo userInfo, Integer type, Integer pageNum, DemandInfo demandInfo) {
        if (StringUtils.isBlank(type.toString())) {
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        if (type == 1) { // 我发布的需求
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = homeService.listMyPublishDemand(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 2) { // 供应
            PageHelper.startPage(pageNum,10);
            List<MyPublishVO> myPublishList = supplyService.listMyPublishSupply(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 3) { // 招聘
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = jobService.listMyPublishRecruit(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 4) { // 求职
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = jobService.listMyPublishApply(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 5) { // 共享技术
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = userDataService.listMyPublishInfo(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 6) { // 共享视频
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = userDataService.listMyPublishVideo(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 7) { // 问答
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = askQuestionsService.listMyPublishQuiz(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 8) { // 动态
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = homeService.listMyPublishLife(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else if (type == 9) { // 四闲
            PageHelper.startPage(pageNum, 10);
            List<MyPublishVO> myPublishList = supplyService.listMyPublishIdel(userInfo.getUserId());
            return Response.List().ok().addParams(myPublishList);
        } else {
            return Response.custom().failure("没有找到此类型!");
        }
    }

    /**
     * 接单情况
     * @param demandId
     * @return
     */
    @RequestMapping("/demand/acceptState")
    public Response demandAcceptState(Integer demandId, Integer pageNum) {
        if (pageNum == null || demandId == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        PageHelper.startPage(pageNum, 10);
        List<DemandAcceptStateVO> demandAcceptStateList = demandService.listDemandAcceptState(demandId);
        return Response.List().ok().addParams(demandAcceptStateList);
    }

    /**
     * 发布需求
     * @param info
     * @param demandInfo
     * @return
     */
    @RequestMapping(value = "/demand/add",method = RequestMethod.POST)
    public Response addDemand(@CurrentUser UserInfo info,DemandInfo demandInfo){
        if (StringUtils.isBlank(demandInfo.getDemandType()) || StringUtils.isBlank(demandInfo.getDemandDescription())
            || StringUtils.isBlank(demandInfo.getModile()) || demandInfo.getIsExpedited() == null || StringUtils.isBlank(demandInfo.getLongitude())
            || StringUtils.isBlank(demandInfo.getLatitude())){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        demandInfo.setUserId(info.getUserId());
        demandInfo.setTitle(demandInfo.getTitle());
        demandInfo.setIsReview(getMarginInfo().getIsReview());
        demandInfo.setDemandType(demandInfo.getDemandType());
        demandInfo.setModile(demandInfo.getModile());
        demandInfo.setLongitude(demandInfo.getLongitude());
        demandInfo.setLatitude(demandInfo.getLatitude());
        demandInfo.setDemandDescription(demandInfo.getDemandDescription());
        demandInfo.setIsExpedited(demandInfo.getIsExpedited());
        demandInfo.setVideos(demandInfo.getVideos());
        demandInfo.setFirstVideoPhotos(demandInfo.getFirstVideoPhotos());
        demandInfo.setPhotos(demandInfo.getPhotos());
        demandInfo.setAudio(demandInfo.getAudio());
        homeService.addDemand(demandInfo);
        return Response.custom().ok();
    }

    /**
     * 获取附近的人信息
     * @param longitude
     * @param latitude
     * @return
     */
    @PostMapping("/people/nearby")
    @LoginRequired
    @ResponseBody
    public Response getPeopleNearby(double longitude,double latitude){
        // 千米
        int radius = 10;
        SpatialContext geo = SpatialContext.GEO;
        Rectangle rectangle = geo.getDistCalc().calcBoxByDistFromPt(geo.makePoint(longitude, latitude), radius * DistanceUtils.KM_TO_DEG, geo, null);
        System.out.println(rectangle.getMinX() + "-" + rectangle.getMaxX());// 经度范围
        System.out.println(rectangle.getMinY() + "-" + rectangle.getMaxY());// 纬度范围
        List<UserInfo> infos = infoService.peopleNearby(String.valueOf(rectangle.getMinX()),String.valueOf(rectangle.getMaxX())
                ,String.valueOf(rectangle.getMinY()),String.valueOf(rectangle.getMaxY()));
        return Response.custom().ok().addParams(infos);
    }

    /**
     * 发布动态
     * @param info
     * @param life
     * @return
     */
    @PostMapping("/instant/add")
    @ResponseBody
    public Response addInstant(@CurrentUser UserInfo info, UserInstantLife life){
        if (StringUtils.isBlank(life.getContent())){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        life.setUserId(info.getUserId());
        life.setIsReview(getMarginInfo().getIsReview());
        homeService.addInstantLift(life);
        return Response.custom().ok();
    }

    /**
     * 获取动态列表
     * @param pageNum
     * @return
     */
    @PostMapping("/instant/list")
    @LoginRequired
    @ResponseBody
    public Response addInstant(Integer pageNum){
        if (pageNum == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        PageHelper.startPage(pageNum,10);
        List<UserInstantLife> blackUserList = homeService.getUserInstantLiftList();

        PageInfo pageInfo = new PageInfo(blackUserList,10);
        if(pageNum > pageInfo.getPages()){
            return Response.custom().ok().addParams(new List[0]);
        }else{
            return Response.custom().ok().addParams(pageInfo.getList());
        }
    }

    /**
     * 查看动态详情
     * @param info
     * @param instantId
     * @return
     */
    @PostMapping("/instant/details")
    @ResponseBody
    public Response getInstantInfoDetails(@CurrentUser UserInfo info,String instantId){
        if (StringUtils.isBlank(instantId)){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("details",homeService.getUserInstantLifeDetails("l.id",instantId,info.getUserId()));
        PageHelper.startPage(1,10);
        PageInfo pageInfo = new PageInfo(homeService.getInstantLifeComment("1",instantId),10);
        if (pageInfo.getSize() == 0){
            map.put("comment",new List[0]);
        }else{
            if (pageInfo.getList().get(0) != null){
                map.put("comment",pageInfo.getList());
            }else{
                map.put("comment",new List[0]);
            }
        }
        return Response.custom().ok().addParams(map);
    }

    /**
     * 分享
     * @param info
     * @param type
     * @param typeId
     * @return
     */
    @PostMapping("/instant/share")
    @ResponseBody
    public Response instantShare(@CurrentUser UserInfo info,String typeId,String type){
        if (StringUtils.isBlank(typeId) || StringUtils.isBlank(type)){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        switch (type){
            //动态
            case "1":
                if (homeService.instantInfoShare("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //需求
            case "2":
                if (homeService.instantInfoDemand("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //招聘
            case "3":
                if (homeService.instantInfoRecruitment("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //求职
            case "4":
                if (homeService.instantInfotoApplyForAJob("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //临工
            case "5":
                if (homeService.instantInfoTemporaryWork("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //供应
            case "6":
                if (homeService.instantInfoSupply("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //四闲
            case "7":
                if (homeService.instantInfoFourLeisureHours("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }
                //专家
            case "8":
                if (homeService.instantInfoExperts("l.id",typeId,info.getUserId())){
                    return Response.custom().ok();
                }else{
                    return Response.custom().failure("没有找到此ID");
                }

            default:
                return Response.custom().failure("没有找到此类型!");

        }
    }

    /**
     * 评论
     * @param info
     * @param comment
     * @return
     */
    @PostMapping("/comment/add")
    @ResponseBody
    public Response addComment(@CurrentUser UserInfo info,InstantLifeComment comment){
        homeService.addComment(info, comment);
        return Response.custom().ok();
    }

    /**
     * 获取评论回复列表
     * @param commentId
     * @param pageNum
     * @return
     */
    @PostMapping("/comment/reply/list")
    @LoginRequired
    @ResponseBody
    public Response replyCommentList(String commentId,Integer pageNum){
        if (StringUtils.isBlank(commentId) || pageNum == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        PageHelper.startPage(pageNum,10);
        List<CommentReplyList> commentReplyLists = homeService.getReplyList(commentId);
        PageInfo pageInfo = new PageInfo(commentReplyLists,10);
        if(pageNum > pageInfo.getPages()){
            return Response.custom().ok().addParams(new List[0]);
        }else{
            return Response.custom().ok().addParams(pageInfo.getList());
        }
    }

    /**
     * 添加评论回复
     * @param info
     * @param reply
     * @return
     */
    @PostMapping("/comment/reply/add")
    @ResponseBody
    public Response addReplyComment(@CurrentUser UserInfo info,CommentReply reply){
        if (StringUtils.isBlank(reply.getContent()) || reply.getReplyType() == null || reply.getCommentId() == null){
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        if (reply.getReplyType() == 2){
            if (StringUtils.isBlank(reply.getReplyId())){
                return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
            }
        }
        String toUid = homeService.getCommentDetails(reply.getCommentId()).getFromUid();
        if (toUid == null){
            return Response.custom().failure("评论ID未找到!!");
        }
        reply.setToUid(toUid);
        reply.setFromUid(info.getUserId());
        homeService.addReplyComment(reply);
        return Response.custom().ok();
    }

    /**
     * 帮他点亮
     * @param userInfo 当前登录用户信息
     * @param userId 要帮助点亮的人的id
     * @param supplyId 供应id
     * @return
     */
    @PostMapping("/supply/helpToLighten")
    public Response helpToLighten(@CurrentUser UserInfo userInfo, String userId, Integer supplyId) {
        if (StringUtils.isBlank(userId) || supplyId == null) {
            return Response.custom().failure("缺少请求参数,请重新核对后再提交!");
        }
        if (supplyService.getSupplyDetails(supplyId, null) == null) {
            return Response.custom().failure("该供应不存在!");
        }
        if (supplyService.getSupplyLightenInfo(new SupplyLighten(userId, supplyId, userInfo.getUserId())) != null) {
            return Response.custom().failure("您已帮他点亮过该供应，无法重复点亮!");
        }
        int supplyLightenTimes = supplyService.countSupplyLighten(userId, supplyId);
        if (supplyLightenTimes < 3) {
            supplyService.insertSupplyLightenInfo(new SupplyLighten(userId, supplyId, userInfo.getUserId()));
            return Response.custom().ok();
        } else {
            return Response.custom().failure("该请求已点亮!");
        }
    }


}
